package cn.iocoder.yudao.module.social.controller.app.content;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.social.controller.app.content.vo.*;
import cn.iocoder.yudao.module.social.convert.content.AppContentConvert;
import cn.iocoder.yudao.module.social.dal.dataobject.content.ContentDO;
import cn.iocoder.yudao.module.social.service.content.AppContentConvertService;
import cn.iocoder.yudao.module.social.service.content.ContentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.module.social.enums.ErrorCodeConstants.CONTENT_NOT_EXISTS;

@Tag(name = "用户端 - 内容")
@RestController
@RequestMapping("/social/content")
@Validated
public class AppContentController {

    @Resource
    private ContentService contentService;

    @Resource
    private AppContentConvertService appContentConvertService;

    @PostMapping("/create")
    @Operation(summary = "创建内容")
    public CommonResult<Long> createContent(@Valid @RequestBody AppContentCreateReqVO createReqVO) {
        // 获取当前登录用户ID
        Long currentUserId = SecurityFrameworkUtils.getLoginUserId();

        // 转换为管理端VO并设置作者ID
        var adminCreateReqVO = AppContentConvert.INSTANCE.convertToAdmin(createReqVO, currentUserId);

        return success(contentService.createContent(adminCreateReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新内容")
    public CommonResult<Boolean> updateContent(@Valid @RequestBody AppContentUpdateReqVO updateReqVO) {
        // 获取当前登录用户ID
        Long currentUserId = SecurityFrameworkUtils.getLoginUserId();

        // 校验内容是否存在且属于当前用户
        ContentDO existingContent = contentService.getContent(updateReqVO.getId());
        if (existingContent == null) {
            return CommonResult.error(CONTENT_NOT_EXISTS);
        }

        // 检查权限：只有作者本人或管理员可以编辑
        boolean isAuthor = currentUserId.equals(existingContent.getAuthorId());
        boolean isAdmin = currentUserId.equals(1L); // 假设用户ID=1为管理员
        if (!isAuthor && !isAdmin) {
            return CommonResult.error(403, "无权限编辑此内容");
        }

        // 转换为管理端VO
        var adminUpdateReqVO = AppContentConvert.INSTANCE.convertToAdmin(updateReqVO);
        adminUpdateReqVO.setAuthorId(existingContent.getAuthorId()); // 保持原作者不变

        contentService.updateContent(adminUpdateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除内容")
    @Parameter(name = "id", description = "编号", required = true)
    public CommonResult<Boolean> deleteContent(@RequestParam("id") Long id) {
        // 获取当前登录用户ID
        Long currentUserId = SecurityFrameworkUtils.getLoginUserId();

        // 校验内容是否存在且属于当前用户
        ContentDO existingContent = contentService.getContent(id);
        if (existingContent == null) {
            return CommonResult.error(CONTENT_NOT_EXISTS);
        }

        // 检查权限：只有作者本人或管理员可以删除
        boolean isAuthor = currentUserId.equals(existingContent.getAuthorId());
        boolean isAdmin = currentUserId.equals(1L); // 假设用户ID=1为管理员
        if (!isAuthor && !isAdmin) {
            return CommonResult.error(403, "无权限删除此内容");
        }

        contentService.deleteContent(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得内容")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<AppContentRespVO> getContent(@RequestParam("id") Long id) {
        Long currentUserId = SecurityFrameworkUtils.getLoginUserId();

        ContentDO content = contentService.getContent(id);
        if (content == null) {
            return CommonResult.error(CONTENT_NOT_EXISTS);
        }

        // 检查星球权限：只能查看同一星球的内容
        // 这里可以根据实际需求添加星球权限检查逻辑

        AppContentRespVO respVO = appContentConvertService.convertWithPermissions(content, currentUserId);
        return success(respVO);
    }

    @GetMapping("/page")
    @Operation(summary = "获得内容分页")
    public CommonResult<PageResult<AppContentRespVO>> getContentPage(@Valid AppContentPageReqVO pageReqVO) {
        Long currentUserId = SecurityFrameworkUtils.getLoginUserId();

        // 确保星球ID不为空
        if (pageReqVO.getPlanetId() == null) {
            return CommonResult.error(400, "星球编号不能为空");
        }

        // 转换为管理端分页查询VO
        var adminPageReqVO = new cn.iocoder.yudao.module.social.controller.admin.content.vo.ContentPageReqVO();
        adminPageReqVO.setPageNo(pageReqVO.getPageNo());
        adminPageReqVO.setPageSize(pageReqVO.getPageSize());
        adminPageReqVO.setAuthorId(pageReqVO.getAuthorId());
        adminPageReqVO.setContainerId(pageReqVO.getContainerId());
        adminPageReqVO.setPlanetId(pageReqVO.getPlanetId());
        adminPageReqVO.setTitle(pageReqVO.getTitle());
        adminPageReqVO.setStatus(pageReqVO.getStatus());
        adminPageReqVO.setCreateTime(pageReqVO.getCreateTime());

        PageResult<ContentDO> pageResult = contentService.getContentPageByPlanet(adminPageReqVO, pageReqVO.getPlanetId());
        PageResult<AppContentRespVO> result = appContentConvertService.convertPageWithPermissions(pageResult, currentUserId);

        return success(result);
    }

    @GetMapping("/my-list")
    @Operation(summary = "获得我的内容列表")
    @Parameter(name = "planetId", description = "星球编号", required = true, example = "1")
    public CommonResult<List<AppContentRespVO>> getMyContentList(@RequestParam("planetId") Long planetId) {
        Long currentUserId = SecurityFrameworkUtils.getLoginUserId();

        List<ContentDO> contents = contentService.getContentListByAuthorAndPlanet(currentUserId, planetId);
        List<AppContentRespVO> result = appContentConvertService.convertListWithPermissions(contents, currentUserId);

        return success(result);
    }

    @GetMapping("/list-by-container")
    @Operation(summary = "根据容器获得内容列表")
    @Parameter(name = "containerId", description = "容器编号", required = true, example = "1")
    @Parameter(name = "planetId", description = "星球编号", required = true, example = "1")
    public CommonResult<List<AppContentRespVO>> getContentListByContainer(
            @RequestParam("containerId") Long containerId,
            @RequestParam("planetId") Long planetId) {
        Long currentUserId = SecurityFrameworkUtils.getLoginUserId();

        List<ContentDO> contents = contentService.getContentListByContainerAndPlanet(containerId, planetId);
        List<AppContentRespVO> result = appContentConvertService.convertListWithPermissions(contents, currentUserId);

        return success(result);
    }

}
